use yew::prelude::*;
use yew_router::prelude::*;

use crate::{
  components::{crate_list::CrateList, header::Header},
  contexts::CurrentUserContext,
  pages::slidebar::Slidebar,
  Route,
};

#[function_component]
pub fn Crates() -> Html {
  let loading = html! { <p>{"loading..."}</p> };

  let current_user_ctx = use_context::<CurrentUserContext>()
    .expect("Current user context is missing");

  match &current_user_ctx.token {
    Some(token) => {
      html! {
        <>
          <Header/>
          <Slidebar/>
          <div>
            <Suspense fallback={loading}>
              <CrateList token={token.clone()}/>
            </Suspense>
          </div>
        </>
      }
    }
    None => html! {
      <Redirect<Route> to={Route::Crates}/>
    },
  }
}
